"""
scons build file

PEM

@author: Jean-Lou Dupont
"""
import os
import shutil

from helpers import *


Help("""\
   'scons' to build the libraries (release and debug),
   'scons deb' to build the .deb package
   'scons rel' to release the package to tags/debian repository
   'scons install' to install on local machine
   'scons installlib' to install the libraries on local machine
""")

# LIST MODULES
# ============
includes = ['#pem',]

list_modules = [	'#pem/common',
					'#pem/drv_mng',
					'#pem/drv_ifk',
				]


modules = []
for module in list_modules:
	modules.append( {	'script'  : "%s/SConscript" % module,
						'build'   : module,
						'release' : Environment(CPPPATH=[module+'/include']+includes),
						'debug'   : Environment(CPPPATH=[module+'/include']+includes, CPPFLAGS="-D_DEBUG -g", _DEBUG='1')
					} )

for module in modules:
	SConscript(module['script'], build_dir=module['build']+'/release', exports={'env':module['release']})
	SConscript(module['script'], build_dir=module['build']+'/debug',   exports={'env':module['debug']})

this_lib = "pem"

libs  = [('./pem/common/%s/libpem_common%s.so','../packages/debian/usr/lib/libpem_common%s-%s.so')
		]
		
execs = [('./pem/drv_ifk/%s/pem_drv_ifk%s', '../packages/debian/usr/bin/pem_drv_ifk%s-%s'),
		 ('./pem/drv_mng/%s/pem_drv_mng%s', '../packages/debian/usr/bin/pem_drv_mng%s-%s')
		] 
		
all = libs + execs

epem = [
		{'params':True,  'dir': True,  'src': './epem/src',     'dst':'../../project/packages/debian/usr/lib/erlang/lib/epem-%s/src'},	   
		{'params':True,  'dir': True,  'src': './epem/ebin',    'dst':'../../project/packages/debian/usr/lib/erlang/lib/epem-%s/ebin'},
		{'params':False, 'dir': False, 'src': './epem/epem.py', 'dst':'../../project/packages/debian/etc/init.d/epem'},
		]


env = Environment()


# BUILDING .deb PACKAGE
# =====================
if 'deb' in COMMAND_LINE_TARGETS:

	print "Preparing .deb package"
	try:
		version = read_version()
		print """scons: building version [%s]""" % version
		
		print """scons: cloning files to packages/debian"""
		for one in all:
			src, dst = one
			#release
			print "scons: cloning [%s]" % (src % ('release', ''))
			shutil.copy(	src % ('release', ''), 
							dst % ('',        version) )
			#debug
			shutil.copy(	src % ('debug',  '_debug'), 
							dst % ('_debug',  version) )
		
		for one in epem:
			src   = one['src']
			dst   = one['dst']
			isdir = one['dir']
			params= one['params']

			print "> cloning [%s]" % src
			if isdir:
				safe_copytree(	src , dst % version, skip_dirs=[".svn" ] )#, "_old", "_old2"] )
			else:
				if params:
					shutil.copy(src, dst % version)
				else:
					shutil.copy(src, dst)
			
		
		
		## AT THIS POINT, ALL THE FILES SHOULD BE UNDER THE /packages/debian
		## HIERARCHY READY FOR PACKAGING
		## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
		
		print """scons: removing /tmp directory"""
		shutil.rmtree('/tmp/%s_deb' % this_lib, ignore_errors=True)

		print """scons: cloning ./packages/debian to /tmp directory"""
		safe_copytree('../packages/debian', '/tmp/%s_deb' % this_lib, skip_dirs=['.svn',], dir_mode=0775, make_dirs=True)

		print """scons: adjusting version in control files"""
		c_path = '/tmp/%s_deb/DEBIAN' % this_lib
		params = {'version':version}
		adjust_control_files(params, c_path)
		
		print """scons: adjusting permissions for `dkpg-deb` command-line"""
		recursive_chmod("/tmp/%s_deb" % this_lib, mode=0775)

		print """scons: copying beam files"""
		safe_copytree("./epem/ebin", "/tmp/%s_deb/usr/share/pem/bin" % this_lib)


	except Exception,e:
		print "*** ERROR [%s] ***" % e
	
env.Command("deb", "/tmp/%s_deb" % this_lib, "dpkg-deb --build $SOURCE")
	
	
# RELEASING
#
#  The 'deb' command is assumed to have been performed.
#  The 'deb' package is assumed to be sitting in /tmp
#
# =========
if 'rel' in COMMAND_LINE_TARGETS:

	# extract "version"
	version = read_version()
	print "scons: RELEASING version %s" % version
	
	name = "%s_%s-1_i386.deb" % (this_lib, version)
	path = "/tmp/%s" % name
	print "scons: renaming debian package: %s" % name
	shutil.copy('/tmp/%s_deb.deb' % this_lib, path)

	print "scons: copying [%s] to repo in dists/main/binary-i386" % path
	shutil.copy(path, "../../../dists/stable/main/binary-i386")

	print "scons: copying [%s] to repo in dists/main/binary-amd64" % path
	shutil.copy(path, "../../../dists/stable/main/binary-amd64")
	
	debian_path = "../../../dists/stable/main/binary-i386/%s" % name
	print "scons: running dpkg-scanpackages  [%s]" % debian_path
	os.system("cd ../../.. && dpkg-scanpackages -m dists/stable/main/binary-i386 /dev/null | gzip -9c > dists/stable/main/binary-i386/Packages.gz")

	debian_path = "../../../dists/stable/main/binary-amd64/%s" % name
	print "scons: running dpkg-scanpackages  [%s]" % debian_path
	os.system("cd ../../.. && dpkg-scanpackages -m dists/stable/main/binary-amd64 /dev/null | gzip -9c > dists/stable/main/binary-amd64/Packages.gz")

	
	print "scons: removing sources archive build directory"
	try:    shutil.rmtree("/tmp/%s/%s" % (this_lib, this_lib))
	except: pass
	
	print "scons: creating sources archive"
	safe_copytree('.', '/tmp/%s/%s' % (this_lib,this_lib), skip_dirs=['.svn', 'debug', 'release'], dir_mode=0775, make_dirs=True)
	
	print "scons: removing unecessary files"
	os.system("rm /tmp/%s/%s/.sconsign.dblite" % (this_lib, this_lib))
	os.system("rm -r /tmp/%s/%s/*.pyc" % (this_lib, this_lib))
	
	print "scons: creating ZIP archive"
	os.system("cd /tmp/%s && zip -r /tmp/%s-sources-%s.zip %s -x *.svn* *.os *.so *.LOG *.DAT *.settings* *.cproject* *.project* *.pydevproject* *old* *.prefs" % (this_lib, this_lib, version, this_lib))


if 'up' in COMMAND_LINE_TARGETS:
	import gcupload as gc
	
	version = read_version()

	print "scons: uploading to Google Code"
	user = get_gcuser()
	pwd  =  get_gcpwd()
	
	#upload(file, project_name, user_name, password, summary, labels=None)
	src = "/tmp/%s-sources-%s.zip" % (this_lib, version)
	gc.upload(src, "phidget-erlang-manager", user, pwd, "sources archive", ["sources", "featured"])
	
	deb = "/tmp/%s_%s-1_i386.deb" % (this_lib, version)
	gc.upload(deb, "phidget-erlang-manager", user, pwd, "debian binary-i386", ["Type-Package", "OpSys-Linux", "featured"])
		
